package cn.tedu.system.oa.notice.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

//@Component
//@ServerEndpoint("/websocket-endpoint")
public class CustomWebSocketEndpoint {
    // 存储所有连接的WebSocket会话,
    private static final Map<String, Session> sessions = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        //userId参数存储
        String userId = session.getQueryString().split("=")[1];
        sessions.put(userId,session);
        System.out.println("连接成功,userId:" + session);
    }
    @OnMessage
    public void onMessage(String message, Session session){
        System.out.println("消息到达客户端:" + message);
    }
    @OnClose
    public void onClose(Session session){
        String userId = session.getQueryString().split("=")[1];
        sessions.remove(userId);
        System.out.println("连接关闭,userId:" + userId);
    }

    @OnError
    public void onError(Session session,Throwable throwable){
        System.out.println("发生错误:" + throwable.getMessage());
    }

    //向指定用户发送消息
    public static void sendMessageToUser(String userId,String message) throws IOException {
        Session session = sessions.get(userId);
        System.out.println(session);
        if (session != null && session.isOpen()) {
            session.getBasicRemote().sendText(message);
        }
    }

}
